﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Ice.Toolkit.Web
{
    public class DownLoad : System.Web.UI.Page
    {
        private int _bufferLength = 10240;    //缓冲区大小10K

        protected int BufferLength { get { return _bufferLength; } set { _bufferLength = value; } }

        public void LoadFile(string fileName)
        {
            var buffer = new Byte[BufferLength];

            using (Stream stream = new FileStream(fileName, FileMode.Open))
            {
                Response.AddHeader("Accept-Ranges", "bytes");

                long p = 0, fLength = stream.Length;

                if (Request.Headers["Range"] != null)
                {
                    Response.StatusCode = 206;
                    p = long.Parse(Request.Headers["Range"].Replace("bytes=", "").Replace("-", ""));
                }

                if (p != 0)
                {
                    Response.AddHeader("Content-Range", "bytes " + p.ToString() + "-" + ((long)(fLength - 1)).ToString() + "/" + fLength.ToString());
                }

                Response.AddHeader("Content-Length", ((long)(fLength - p)).ToString());
                Response.ContentType = "application/octet-stream";
                Response.AddHeader("Content-Disposition", "attachment; filename=" + System.Web.HttpUtility.UrlEncode(System.Text.Encoding.GetEncoding(65001).GetBytes(Path.GetFileName(fileName))));

                stream.Position = p;
                fLength -= p;

                while (fLength > 0)
                {
                    if (Response.IsClientConnected)
                    {
                        var l = stream.Read(buffer, 0, BufferLength);

                        Response.OutputStream.Write(buffer, 0, l);
                        Response.OutputStream.Flush();
                        fLength -= l;
                    }
                    else
                    {
                        break;
                    }
                }
            }
        }
    }
}
